package serialization;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Random;

public class Worm implements Serializable{

	private static Random rand = new Random();

	private Data[] d = { new Data(rand.nextInt(10)),
			new Data(rand.nextInt(10)), new Data(rand.nextInt(10)) };
	
	private Worm next;
	private char c;
	// Value of i == number of segments
	public Worm(int i, char x) {
		System.out.println("Worm constructor: " + i);
		c = x;
		if(--i>0)
			next = new Worm(i, (char)(x + 1));
	}
	
	public String toString() {
		StringBuilder sbuilder = new StringBuilder();
		sbuilder.append(':').append(c).append('(');
		for(int i=0;i<d.length;i++) {
			sbuilder.append(d[i]);
		}
		sbuilder.append(')');
		if(next!=null) {
			sbuilder.append(next);
		}
		return sbuilder.toString();
	}
	
	public static void main(String[] args) throws ClassNotFoundException, IOException{
		Worm w = new Worm(6,'a');
		System.out.println("w = " + w);
		
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("worm.out"));
		oos.writeObject("Worm storage: file\n");
		oos.writeObject(w);
		oos.close(); // Also flushes output
		
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("worm.out"));
		String s = (String)ois.readObject();
		Worm w2 = (Worm)ois.readObject();
		System.out.println(s + "w2 = " + w2);
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos2 = new ObjectOutputStream(baos);
		oos2.writeObject("Worm storage: byteArray\n");
		oos2.writeObject(w2);
		//oos2.flush();
		oos2.close();
		byte[] buff = baos.toByteArray();
		
		ObjectInputStream ois2 = new ObjectInputStream(new ByteArrayInputStream(buff));
		s = (String)ois2.readObject();
		Worm w3 = (Worm)ois2.readObject();
		System.out.println(s + "w3 = " + w3);
	}
}

class Data implements Serializable {
	private int n;

	public Data(int n) {
		this.n = n;
	}

	public String toString() {
		return Integer.toString(n);
	}
}